package cn.zn.framework.common.abs;

import cn.hutool.core.util.StrUtil;
import cn.zn.framework.common.xss.SQLFilter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public abstract class AbsPage<T> {
    private Long offset;
    @ApiModelProperty(value = "每页显示记录数", example = "10")
    private Long limit;
    private String sort;
    private String order;

    /**
     * 得到PAGE对象
     *
     * @return
     */
    public IPage<T> getPage() {
        //分页参数
        long curPage = 1;
        long myLimit = 10;

        if (this.limit != null) {
            myLimit = this.limit;
        }
        if (this.offset != null && this.offset > 0L) {
            curPage = this.offset / myLimit + 1;
        }

        //分页对象
        Page<T> page = new Page<>(curPage, myLimit);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = StrUtil.isNotEmpty(this.sort) ? SQLFilter.sqlInject(this.sort) : null;
        if (StrUtil.isNotEmpty(orderField)) {
            String myOrder = SQLFilter.sqlInject(this.order);
            if (myOrder.equals("asc")) {
                page.addOrder(OrderItem.asc(orderField));
            } else {
                page.addOrder(OrderItem.desc(orderField));
            }
        }
        return page;
    }

    public abstract Wrapper<T> getWrapper();
}
